import React, { Component } from 'react'
import "./exam.scss"
import Header from '../../components/Header/header'
import Footer from '../../components/Footer/footer'
import { get, UrlSearch } from '../../axios/localstorage'
import { getApiExamInfo , getApiInsertRecordExamMaster } from "../../axios/api"
import { message } from 'antd'


export default class exam extends Component {

    state = {
        min:0,
        second:0,
        data:{},
        question:[],
        activeIndex:0,
        qdata:{
            answer:[]
        },
        outAlert:false,
        noneAlert:false,
        outPgae:'',

        score:0,
        alert:false,
        timer:'',
    }


    componentWillMount(){
        window.scroll(0,0);
        let id = UrlSearch('id');
        let chapter_id = UrlSearch('chapter_id');
        let content_id = UrlSearch('content_id');

        this.setState({
            id,
            chapter_id,
            content_id
        })
        setTimeout(()=>{
            this.getData();
        },50)
        
    }

    componentDidMount(){
        window.history.pushState(null, null, document.URL);
        var that = this;
        window.addEventListener('popstate', function () {
            // window.history.pushState(null, null, document.URL);
            console.log(111);
            that.setState({outAlert:true})
        });
    }

    getData=()=>{
        let param = {
            token:get('token'),
            course_id:this.state.id,
            chapter_id:this.state.chapter_id,
            content_id:this.state.content_id,
        }

        getApiExamInfo(param)
        .then( req =>{
            if(req.data.code === 1){
                let data = req.data.data;
                this.setState({
                    data,
                    min:data.time,
                    question:data.question,
                    qdata:data.question[0],
                    activeIndex:0,
                })
                this.countTime();

                setTimeout(()=>{
                    this.countHadAnswer();
                },50)
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    countHadAnswer=()=>{
        let question = this.state.question;

        for(var i=0;i<question.length;i++){
            for(var j=0;j<question[i].answer.length;j++){
                if(question[i].answer[j].chosen){
                    console.log(123);
                    question[i].hadChosen = 1; 
                }
            }
        }

        console.log(question);

        this.setState({
            question
        })
    }

    countTime=()=>{
        let timer = setInterval(()=>{

            let min = this.state.min;
            let second = this.state.second;

            if(second <= 0 ){
                min --;
                second = 59;
            }else{
                second --;
            }

            if(min === 0 && second === 0){
                clearInterval(this.state.timer);
            }

            this.setState({
                min,
                second
            })
    
        },1000)

        this.setState({
            timer
        })
    }

    gotoChooseQuestion=(index)=>{
        let activeIndex = this.state.activeIndex;
        let question = this.state.question;
        let qdata = question[activeIndex];
        if(qdata.type === 1){
            for(var i=0;i<qdata.answer.length;i++){
                qdata.answer[i].chosen = 0;
            }

            qdata.answer[index].chosen = 1;
        }else{
            
            if(qdata.answer[index].chosen){
                qdata.answer[index].chosen = 0;
            }else{
                qdata.answer[index].chosen = 1;
            }
        }

        this.setState({
            question,
            qdata
        })

        setTimeout(()=>{
            this.countHadAnswer();
        },50)
    }

    gotoPrev=()=>{
        if(this.state.activeIndex === 0){
            return false;
        }else{
            let qdata = this.state.question[this.state.activeIndex - 1];
            this.setState({
                qdata,
                activeIndex:this.state.activeIndex - 1
            })
        }
    }

    gotoNext=()=>{
        if(this.state.activeIndex + 1 >= this.state.question.length){
            message.info('当前已经是最后一题了，可以提交答案!')
            return false;
        }else{
            let qdata = this.state.question[this.state.activeIndex + 1];
            this.setState({
                qdata,
                activeIndex:this.state.activeIndex + 1
            })
        }
    }

    gotoOtherQuestion=(index)=>{
        let qdata = this.state.question[index];
        this.setState({
            qdata,
            activeIndex:index
        })
    }

    showOutAlert=(page)=>{
        this.setState({
            outAlert:true,
            outPgae:page
        })
    }

    gotoOutPage=()=>{
        if(this.state.outPgae){
            this.props.history.push(this.state.outPgae);
        }else{
            console.log('111');
            // this.props.history.push('/style');
            // this.props.history.push('/study?id='+this.state.id+'&chapter_id='+this.state.chapter_id+"&content_id="+this.state.content_id);
            window.history.back();
        }
    }

    gotoPush=()=>{
        let question = this.state.question;

        for(var i=0;i<question.length;i++){
            if(!question[i].hadChosen){
                this.setState({
                    noneAlert:true
                })

                return false;
            }
        }


        let param = {
            course_id:this.state.id,
            chapter_id:this.state.chapter_id,
            content_id:this.state.content_id,
            token:get('token'),
            choice:this.state.question,
            time:this.state.min*60+this.state.second,
            type:get('type')?get('type'):0,
        }

        getApiInsertRecordExamMaster(param)
        .then( req =>{
            if(req.data.code === 1){
                let data = req.data.data;
                clearInterval(this.state.timer);
                this.setState({
                    alert:true,
                    second:0,
                    min:0,
                    score:parseInt(data)
                })
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    returnExam=()=>{

        this.setState({
            alert:false
        })
        
        this.getData();
    }

    gotoPage=(page)=>{
        this.props.history.push(page);
    }

    render() {
        return (
            <div className="exam">
                <Header show="1" showOutAlert={this.showOutAlert} />
                <div className="cen">
                    <div className="emain">
                        <div className="ehead">
                            <div className="eleft">
                                <div>
                                    <div className="ename">
                                        <h1>{this.state.data.title}</h1>
                                        <span>{this.state.data.course_title}</span>
                                    </div>
                                    <p>及格分：{this.state.data.pass_score}分｜用时：{this.state.data.time}分钟｜题数：{this.state.data.nums}题</p>
                                </div>
                            </div>
                            <div className="ecen">
                                <div>
                                    <h2>{this.state.min >9?this.state.min:'0'+this.state.min}:{this.state.second>9?this.state.second:'0'+this.state.second}</h2>
                                    <p>剩余时长</p>
                                </div>
                            </div>
                            <div className="eright">
                                <button className="eb1" onClick={()=>{window.history.back();}}>退出考试</button>
                                <button className="eb2" onClick={()=>{this.gotoPush()}}>提交答案</button>
                            </div>
                        </div>

                        <div className="ebox">
                            <div className="eleft">
                                <div className="title">单选试题（{this.state.activeIndex+1}/{this.state.question.length}）</div>
                                <div className="info">
                                    {/* <h1>{this.state.activeIndex+1}.{this.state.qdata.question}</h1> */}
                                    <div>{this.state.activeIndex+1}.
                                        <div className="cont" dangerouslySetInnerHTML={{
                                            __html: this.state.qdata.question
                                        }}></div>
                                    </div>
                                    {
                                        this.state.qdata.answer.map((item,index)=>{
                                            return <div className="i_answer" key={index} onClick={()=>{this.gotoChooseQuestion(index)}}>
                                                        <div className={item.chosen?"span chosen":"span"}>
                                                            <span></span>
                                                        </div>
                                                        {/* <p>{item.choice}</p> */}
                                                        <div className="cont" dangerouslySetInnerHTML={{
                                                            __html: item.choice
                                                        }}></div>
                                                    </div>
                                        })
                                    }

                                    <div className="ebtns">
                                        <button className="eb1" onClick={()=>{this.gotoPrev()}}>上一题</button>
                                        <button className="eb2" onClick={()=>{this.gotoNext()}}>下一题</button>
                                    </div>
                                </div>

                                
                            </div>
                            <div className="eright">
                                <div className="title">试题（{this.state.question.length}）</div>
                                <div className="questions">
                                    {
                                        this.state.question.map((item,index)=>{
                                            return <span 
                                                        onClick={()=>{this.gotoOtherQuestion(index)}}
                                                        style={this.state.activeIndex === index?{background: 'rgba(27, 186, 132, 1)',border:0,color:'#FFFFFF'}:{}} 
                                                        className={item.hadChosen?"i_had":""} key={index}>
                                                        {index+1}
                                                    </span>
                                        })
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <Footer />


                <div className="alert" hidden={!this.state.outAlert}>
                    <div className="abox">
                        <div className="cen">
                            <img alt="" src="assets/imgs/cuowutishi.png" />
                        </div>
                        <h2>退出考试提示</h2>
                        <p>考试途中退出考试则不记录本次考试成绩</p>
                        <p>是否确认退出当前考试，退出选择“退出考试”，继续考试选择“取消”</p>
                        <div className="abtns">
                            <button className="btn1" onClick={()=>{this.gotoOutPage()}}>退出考试</button>
                            <button className="btn2" onClick={()=>{this.setState({outAlert:false})}}>取消</button>
                        </div>
                    </div>
                </div>

                <div className="alert" hidden={!this.state.noneAlert}>
                    <div className="abox">
                        <div className="cen">
                            <img alt="" src="assets/imgs/cuowutishi.png" />
                        </div>
                        <h2>有未答题提示</h2>
                        <p>您还有题未选择答案，请确保所有题目都完成后提交答案。</p>
                        <div className="abtns2">
                            <button className="btn3" onClick={()=>{this.setState({noneAlert:false})}}>好的，我明白了</button>
                        </div>
                    </div>
                </div>

                <div className="alert" hidden={!this.state.alert}>
                    <div className="abox" hidden={this.state.score < this.state.data.pass_score}>
                        <h1>{this.state.score}</h1>
                        <h2 className="hw2">恭喜通过考试</h2>
                        <p>恭喜您本次考试分数为{this.state.score}分，已通过及格分数</p>
                        <p>您可在我的考试中查看自己的考试记录</p>
                        <div className="abtns abw2">
                            <button className="btn3" onClick={()=>{this.returnExam()}}>重新考试</button>
                            <button className="btn2" onClick={()=>{this.gotoPage('/mytest')}}>我的考试</button>
                        </div>
                    </div>
                    <div className="abox" hidden={this.state.score >= this.state.data.pass_score}>
                        <h1 className="red">{this.state.score}</h1>
                        <h2 className="hw2">很遗憾未通过考试</h2>
                        <p>很遗憾您本次考试分数为{this.state.score}分，未通过及格分数</p>
                        <p>您可在我的考试中查看自己的考试记录</p>
                        <div className="abtns abw2">
                            <button className="btn3" onClick={()=>{this.returnExam()}}>重新考试</button>
                            <button className="btn2" onClick={()=>{this.gotoPage('/mytest')}}>我的考试</button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}
